#include "ORCL.h"

/* Like printf, but red. Limited to 1000 characters. */
void orcl_red_printf(const char *format, ...)
{	
	#define RED_LIM 1000
	va_list args;
	int i;

	char buf1[RED_LIM], buf2[RED_LIM];
	memset(buf1, 0, RED_LIM);
	memset(buf2, 0, RED_LIM);

    va_start(args, format);

	/* Marshal the stuff to print in a buffer */
	vsnprintf(buf1, RED_LIM, format, args);

	/* Probably a bad check for buffer overflow */
	for(i = RED_LIM - 1; i >= RED_LIM - 50; i --) {
		assert(buf1[i] == 0);
	}

	/* Add markers for red color and reset color */
	snprintf(buf2, 1000, "\033[31m%s\033[0m", buf1);

	/* Probably another bad check for buffer overflow */
	for(i = RED_LIM - 1; i >= RED_LIM - 50; i --) {
		assert(buf2[i] == 0);
	}

	printf("%s", buf2);

    va_end(args);
}

// 获取环境变量
char* orcl_getenv(const char *name){
	char *env = getenv(name);
	if(env == NULL) {
		fprintf(stderr, "Environment variable %s not set\n", name);
		assert(false);
	}

	return env;
}

memcached_st* orcl_create_memc(){
	memcached_server_st *servers = NULL;
	memcached_st *memc = memcached_create(NULL);
	memcached_return rc;

	memc = memcached_create(NULL);
	char *registry_ip = orcl_getenv("ORCL_REGISTRY_IP");

	/* We run the memcached server on the default memcached port */
	servers = memcached_server_list_append(servers,
		registry_ip, MEMCACHED_DEFAULT_PORT, &rc);
	rc = memcached_server_push(memc, servers);
	CPE(rc != MEMCACHED_SUCCESS, "Couldn't add memcached server.\n", -1);

	return memc;
}


void APPEND_2_LOG(char* file_name, char* append_string){
    std::ofstream outfile;
    outfile.open(file_name, std::ios::app);

    if(!outfile) //检查文件是否正常打开//不是用于检查文件是否存在
    {
        std::cout<<"can't open LOG file"<< std::endl;
        return;
    }

    outfile << append_string << std::endl;

    outfile.close();
}


